package com.lensong.plugin.sentinel.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.lensong.plugin.sentinel.entity.User;
import com.lensong.plugin.sentinel.entity.proto_output.UserOuterClass;
import com.lensong.statistic.annotation.StatisticRtCost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.Random;

/**
 * Copyright （c）. All rights reserved.
 *
 * @author len.song
 * @date 2022/04/07
 */
@Slf4j
@Controller
@RequestMapping("/proto")
public class ProtoDemoController {

    @RequestMapping(value = "/userProtoEntity", produces = "application/x-protobuf")
    @ResponseBody
    public UserOuterClass.User runDemo1(HttpServletRequest request) {
        UserOuterClass.User.Builder userBuilder = UserOuterClass.User.newBuilder();
        userBuilder.setAge(18);
        userBuilder.setName("张三");
        userBuilder.setComment("今天打游戏连输4盘");
        log.info("header info = {}", JSON.toJSONString(this.getHeders(request)));
        return userBuilder.build();
    }

    @StatisticRtCost(costGtRtms = "${annotation.method.args:}")
    @RequestMapping(value = "/userCommon", produces = "application/json")
    @ResponseBody
    public User runDemo2() throws InterruptedException {
        User userBuilder = new User();
        userBuilder.setAge(18);
        userBuilder.setName("张三");
        userBuilder.setComment("今天打游戏连输4盘");
        Thread.sleep(new Random().nextInt(300));
        return userBuilder;
    }

    /**
     * 获取请求头信息
     *
     * @param request
     * @return
     */
    private Map getHeders(HttpServletRequest request) {
        //2.获得所有头的名称
        Map headerResult = Maps.newHashMap();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {//判断是否还有下一个元素
            String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头
            String header2 = request.getHeader(nextElement);//通过请求头得到请求内容
            headerResult.put(nextElement, header2);
        }
        return headerResult;
    }

}
